package com.xiaoyu.lanling.widget.photo;

import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.viewpager.widget.ViewPager;

import com.xiaoyu.lanling.R;
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity;
import com.xiaoyu.lanling.common.Constant;

import java.util.List;

public class PhotoActivity extends AppCompatToolbarActivity {

    private PhotoViewPager mPhotoViewPager;

    private String mSelectedImageUrl;
    private List<String> mImageUrlList;
    private PhotoPagerAdapter mPhotoPagerAdapter;

    @Override
    protected void onCreateSafelyAfterAppFinishInit(Bundle savedInstanceState) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState);
        setContentView(R.layout.activity_photo);
        initView();
        initData();
    }

    @Override
    protected boolean isSetRequestedOrientationPortrait() {
        return Build.VERSION.SDK_INT != Build.VERSION_CODES.O;
    }

    private void initView() {
        mPhotoViewPager = findViewById(R.id.view_pager);
        mPhotoViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }

    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_IMMERSIVE
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                // Hide the nav bar and status bar
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    private void initData() {
        this.mSelectedImageUrl = getIntent().getStringExtra(Constant.IntentKey.KEY_PHOTO_SELECTED_IMAGE_URL);
        this.mImageUrlList = getIntent().getStringArrayListExtra(Constant.IntentKey.KEY_PHOTO_IMAGE_URL_LIST);

        mPhotoPagerAdapter = new PhotoPagerAdapter(this);
        mPhotoViewPager.setAdapter(mPhotoPagerAdapter);
        mPhotoPagerAdapter.setData(mImageUrlList);

        try {
            int selected = 0;
            int index = mImageUrlList.indexOf(mSelectedImageUrl);
            if (index != -1) {
                selected = index;
            }
            mPhotoViewPager.setCurrentItem(selected, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
